var REFRESHING_PERIOD = 1;//(minute)

var theEditor = null;
var markingHttpObject = null;
var xmlEmailHttp = null;
var xmlEmailSendingHttp = null;

function selectEmailFolderNavigation(nav)
{
	$(nav).parent().children().attr("class", "emailNavigationItem");
	$(nav).attr("class", "emailNavigationSelected");//removeClass('emailNavigationItem').addClass('emailNavigationSelected');
}

function selectEmailItem(evt, row)
{
/*	var emailList = $(row).parent().parent().children();
	emailList.removeClass('emailItemRowSelected');
	emailList.addClass('emailItemRow');
	//alert($(row).parent().parent().children().length);

*/
	
	if ($(row).hasClass('emailTagAndTitle'))
	{
		var emailList = $('#divEmailList').children();
		for (var i = 0; i < emailList.length; i++)
		{
			var emailItem = $(emailList.get(i));
			
			emailItem.removeClass('emailItemRowSelected');
			emailItem.addClass('emailItemRow');
		}
		
		var selectedRow = $(row).parent();
		selectedRow.removeClass('emailItemRow emailUnRead');
		selectedRow.addClass('emailItemRowSelected emailRead');
		var emailId = selectedRow.attr("id");
		markEmail("buzzsystememail", emailId, "read");
		
		//body
		var hidden = $(".bodyContent", selectedRow);
		$('#divEmailDisplay').text("");
		$('#divEmailDisplay').append(unescape(hidden.text()));
		
		//subject
		var subject = $(".emailTitle", selectedRow).text();
		$("#emailDisplaySubject").text("");
		$("#emailDisplaySubject").text(subject);

		//From
		var from = $(".from", selectedRow).text();
		$("#emailDisplaySender").text("");
		$("#emailDisplaySender").text(from);
		
		//TO
		var toList = $(".TOlist", selectedRow).text();
		$("#emailDisplayTOlist").text("");
		$("#emailDisplayTOlist").text(toList);
		
		//CC list
		var strCCs = $(".CClist", selectedRow).text();
		if (strCCs.trim() == "")
		{
			$("#divEmailHeader").removeClass("emailHeader");
			$("#divEmailHeader").addClass("emailHeaderWithoutCC");
		}
		else
		{
			$("#divEmailHeader").removeClass("emailHeaderWithoutCC");
			$("#divEmailHeader").addClass("emailHeader");			
		}
		$("#emailDisplayCClist").text("");
		$("#emailDisplayCClist").text(strCCs);
		
		
		
		$('#emailMinimizedVerticalScrollbar').tinyscrollbar();
		$('#emailMinimizedVerticalScrollbar').tinyscrollbar_update();

		$('#emailMaximizedVerticalScrollbar').tinyscrollbar();
		$('#emailMaximizedVerticalScrollbar').tinyscrollbar_update();

		
		updateUnreadEmailNumber();
		evt.stopPropagation();
	}
//	emailList.removeClass('emailUnRead');
//	emailList.addClass('emailRead');
	
}



function markEmail(account, emailId, readOption)
{
	markingHttpObject = getXmlEmailHttpObject();
	if (markingHttpObject == null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	}

	markingHttpObject.onreadystatechange = function () {};
	markingHttpObject.abort();
	
	var url = "Email?mode=" + (readOption == "read" ? "markAsRead" : "markAsUnread") + "&account=" + encodeURIComponent(account) + "&emailId=" + emailId;
	markingHttpObject.onreadystatechange = function ()
	{
		//getCachedMailListStateChanged(account, emailListContainer);
	};
	
	markingHttpObject.open("GET", url, true);
	markingHttpObject.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
	markingHttpObject.send(null);
}


function rateEmail(star)
{
	$(star).toggleClass("emailStar emailStarMarked");
}

function displayContent(imgSrc)
{
	//$('#imgEmailContent').attr("src", './images-interface/' + imgSrc);
}



///////////////////////////////////////////////////////////////////////
//AJAX Email

function getXmlEmailHttpObject()
{
	var httpObject = null;
	try
	{
	// Firefox, Opera 8.0+, Safari
		httpObject = new XMLHttpRequest();
	}
	catch (e)
	{
	// Internet Explorer
		try
		{
			httpObject = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			httpObject = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return httpObject;
}

function getNewEmailMessages(account, emailListContainer)
{
	xmlEmailHttp = getXmlEmailHttpObject();
	if (xmlEmailHttp == null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	}
		
	xmlEmailHttp.onreadystatechange = function () {};
	xmlEmailHttp.abort();

	var url = "Email" + "?mode=getNew&" + "account" + "=" + encodeURIComponent(account);
	xmlEmailHttp.onreadystatechange = function ()
	{
		stateGetNewChanged(account, emailListContainer);
	};
	
	xmlEmailHttp.open("GET", url, true);
	xmlEmailHttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
	xmlEmailHttp.send(null);
	
	$('#inboxRefreshIcon').show();
}


function stateGetNewChanged(acc, container)
{
	if (xmlEmailHttp.readyState == 4)
	{
		var xmlDoc = xmlEmailHttp.responseXML.documentElement;
		displayEmailMessages(xmlDoc, container);
		
		$("#divInboxNavigation").addClass("emailNavigationHasNewMsg");
		
		$('#divEmailListPanel').tinyscrollbar();
		$('#emailMinimizedVerticalScrollbar').tinyscrollbar();
		$('#inboxRefreshIcon').hide();
		updateUnreadEmailNumber();
	}
}
//Helper
function displayEmailMessages(xmlDoc, containerId)
{	
	var emails = $("EmailItem", xmlDoc);
	for (var i = 0; i < emails.length; i++)
	{
		/*
	    <div class="emailItemRow emailUnRead">
			<div class="emailSelector"></div>
			<div class="emailStar" onclick="rateEmail(this);"></div>
			<div class="emailTagAndTitle" onclick='displayContent("emailContentDisplay.png"); selectEmailItem(event, this);'>
				<span class="emailTag">Sony launching: </span><span class="emailTitle">Street banner, the main banner, sound for the party</span>
			</div>
		</div>
	 */
		var subject = $("Subject", emails[i]);
		
		var strSubject = subject.text();
		var strTolist = $("ToList", emails[i]).text();
		var strCCList = $("CCList", emails[i]).text();
		var strID = $("UniqueID", emails[i]).text();
		var wasRead = $(emails[i]).attr("WasRead");
		if (!wasRead)
			wasRead = "false";
		var strTag = "";
		var strSender = $("From", emails[i]).text();
		var strSentDate =  $("SentDate", emails[i]).text();
		
		var selector = $("<div class='emailSelector'></div>");
		var emailStar = $("<div class='emailStar' onclick='rateEmail(this);'></div>");
		var tagAndTitle = $("<div class='emailTagAndTitle' onclick=\"displayContent('emailContentDisplay.png'); selectEmailItem(event, this);\"></div>");
		var tag = $("<span class='emailTag'>" + strTag + "</span>");
		var title = $("<span class='emailTitle'>" + strSubject + "</span>");
		var sentDate = $("<div class='emailDate'>" + strSentDate + "</div>");
		var sender = $("<div class='emailSender'>" + strSender + "</div>");
		sentDate.attr("title", strSentDate);
		tagAndTitle.append(tag);
		tagAndTitle.append(title);
		tagAndTitle.attr("title", strSubject);
		
		var emailItemClass = "emailUnRead";
		if (wasRead.toLowerCase() == "true"){
			emailItemClass = "emailRead";
		}
		var emailItem = $("<div class='emailItemRow " + emailItemClass + "'></div>");
		emailItem.attr("id", strID);
		emailItem.append(selector);
		emailItem.append(emailStar);
		emailItem.append(tagAndTitle);
		emailItem.append(sentDate);
		emailItem.append(sender);
		
		//Hidden fields
		var content = $("EmailContent", emails[i]);
		var strContent = $("EmailContentPart", content).text();
		var hiddenContent = $("<div class='hiddenFieldContainer' style='display: none;'></div>");
		var toList = $("<div class='TOlist'>" + strTolist + "</div>");			
		var ccList = $("<div class='CClist'>" + strCCList + "</div>");
		var from = $("<div class='from'>" + strSender + "</div>");
		var bodyContent = $("<div class='bodyContent'>" + escape(strContent) + "</div>");
		hiddenContent.append(toList);
		hiddenContent.append(ccList);
		hiddenContent.append(from);
		hiddenContent.append(bodyContent);
		emailItem.append(hiddenContent);
		emailItem.hide();
		
		$("#" + containerId).prepend(emailItem);
		emailItem.show();//"slow");
	}
}

//This function will be fired after finish getting cached emails
function checkForNewMail (account, emailListContainer) {
	setTimeout(function () {
		//alert('check for new mail mesage!');
		getNewEmailMessages(account, emailListContainer);
		checkForNewMail(account, emailListContainer);
	}, REFRESHING_PERIOD * 60 * 1000);
}


function getCachedMailList(account, emailListContainer)
{
	xmlEmailHttp = getXmlEmailHttpObject();
	if (xmlEmailHttp == null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	}

	xmlEmailHttp.onreadystatechange = function () {};
	xmlEmailHttp.abort();

	var url = "Email" + "?mode=readCache&" + "account" + "=" + encodeURIComponent(account);
	xmlEmailHttp.onreadystatechange = function ()
	{
		getCachedMailListStateChanged(account, emailListContainer);
	};
	
	xmlEmailHttp.open("GET", url, true);
	xmlEmailHttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
	xmlEmailHttp.send(null);
}

function getCachedMailListStateChanged(acc, container)
{
	if (xmlEmailHttp.readyState == 4)
	{
		var xmlDoc = xmlEmailHttp.responseXML.documentElement;
		
		displayEmailMessages(xmlDoc, container);
		
		$("#divEmailContentPanel").show();
		$("#loadingIcon").hide();
		$('#inboxRefreshIcon').hide();
		
		$('#divEmailListPanel').tinyscrollbar();
		$('#emailMinimizedVerticalScrollbar').tinyscrollbar();
		
		updateUnreadEmailNumber();
		
		checkForNewMail(acc, container);
		
	}
}



function updateUnreadEmailNumber()
{
	//Update unread inbox email number
	var unreadNum = $("#divEmailList .emailUnRead").length;
	
	if (unreadNum > 0)
	{
		$(".inbox").show();
		$("#inboxUnreadEmailNum").text("" + unreadNum);
	}
	else
	{
		$("#divInboxNavigation").removeClass("emailNavigationHasNewMsg");		
		$(".inbox").hide();		
	}
}

function openNewEmailDialog()
{
	$( "#dialog-form" ).dialog( "open" );
}

function sendEmail(subject, TOList, CCList, BCCList, content)
{
	xmlEmailSendingHttp = getXmlEmailHttpObject();
	if (xmlEmailSendingHttp == null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	}

	xmlEmailSendingHttp.onreadystatechange = function () {};
	xmlEmailSendingHttp.abort();

	var url = "Email" + "?mode=send&" + "subject=" + encodeURIComponent(subject) 
			+ (TOList.trim() != "" ? "&TO=" + encodeURIComponent(TOList) : "")
			+ (CCList.trim() != "" ? "&CC=" + encodeURIComponent(CCList) : "")
			+ (BCCList.trim() != "" ? "&BCC=" + encodeURIComponent(BCCList) : "")
			+ (content.trim() != "" ? "&content=" + encodeURIComponent(content) : "");
	//url = "Email" + "?mode=send";
	xmlEmailSendingHttp.onreadystatechange = function ()
	{
		//getCachedMailListStateChanged(account, emailListContainer);
	};
	
	xmlEmailSendingHttp.open("GET", url, true);
	xmlEmailSendingHttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
	xmlEmailSendingHttp.send(null);	
}

function sendToOutbox()
{
	
}


function saveAsDraft()
{
	
}